package com.xdy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xdy.reggie.common.R;
import com.xdy.reggie.entity.Employee;
import com.xdy.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Resource
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee){
        Employee emp = employeeService.login(employee);
        log.info("密码正确 ===》 {}",emp);
        if (emp == null){
            return R.error("登录失败");
        }
        if (emp.getStatus() == 0){
            log.info("账户已禁用！");
            return R.error("账户已禁用！");
        }
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        log.info("退出登录");
        request.getSession().removeAttribute("employee");
        return R.success("成功退出登录！");
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee){
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        //公共字段使用MyMetaObjectHandler统一处理
//        Long userId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(userId);
//        employee.setUpdateUser(userId);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        employeeService.save(employee);
        return R.success("添加成功！");
    }

    @GetMapping("/page")
    public R<Page<Employee>> page(long page,long pageSize,String name){
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(name),Employee::getName,name);
        employeeService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
     }

    @PutMapping
    public R<String> update(@RequestBody Employee employee){
//        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
//        employee.setUpdateTime(LocalDateTime.now());
        employeeService.updateById(employee);
        return R.success("成功!");
     }

     @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
         Employee employee = employeeService.getById(id);
         return R.success(employee);
     }
}

